const express=require('express')
const config=require('../../config')
const UsersModel=require('../models/users')
const constant=require('../constant')

let router=express.Router()

router.get('/login',async function(req,res,next){
    if(req.cookies.user.token&&req.cookies.user.id&&(await UsersModel.IsRightToken(req.cookies.user.token,req.cookies.user.id))){
        res.render('user/logined',{site:config.site,title:"已登录"})
    }else{
        res.render('user/login',{site:config.site,title:"登录"})
    }
    res.end()
});

router.post('/login',async function(req,res,next){
    try{
        token=await UsersModel.Login(req.body.username,req.body.password)
        res.cookie('user',JSON.stringify({id:await UsersModel.GetIdByUserName(req.body.username),'token':token}))//,'id':await UsersModel.GetIdByUserName(req.body.username)
        //res.cookie('user','id',await UsersModel.GetIdByUserName(req.body.username))//,'id':await UsersModel.GetIdByUserName(req.body.username)
        res.render('user/login-successfully',{site:config.site,title:"登录成功"})
    }catch(err){
        if(err==constant.ERR_WRONG_PASSWORD||err==constant.ERR_NONEXISTENT_USER){
            res.render('user/login-failed',{site:config.site,title:"登录失败"})
        }else{
            throw err;
        }
    }
});

router.get('/logout',async function(req,res,next){
    res.render('user/logout',{site:config.site,title:"登出"})
});

module.exports=router;